<template>
  <el-dialog
    v-model="dialogVisible"
    :title="title"
    top="4%"
    width="75%"
    :before-close="close"
    :close-on-click-modal="false"
    append-to-body
  >
    <el-tabs v-model="tabName" @tab-change="handleTabChange">
      <el-tab-pane label="事项信息" name="matterInfo" />
    </el-tabs>
    <el-scrollbar max-height="61vh" v-loading="loading">
      <div class="mr-4">
        <template v-if="tabName === 'matterInfo'">
          <MatterInfo ref="matterInfo" />
          <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="100px"
          >
            <el-row>
              <el-col :span="8">
                <el-form-item label="责任单位">
                  <unit-select :model-value="formData.unitId" disabled />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="责任领导" prop="responsibleLeaderId">
                  <UserSelect
                    v-model="formData.responsibleLeaderId"
                    :unit-id="formData.unitId"
                    :roleCode="computedLeaderRoleCode"
                    @change="handleChangeLeader"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话">
                  <el-input
                    :model-value="formData.responsibleLeaderPhone"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="责任科室" prop="responsibleDeptId">
                  <unit-select
                    v-model="formData.responsibleDeptId"
                    :unit-id="formData.unitId"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="责任人" prop="responsibleUserId">
                  <UserSelect
                    v-model="formData.responsibleUserId"
                    :department-id="formData.responsibleDeptId"
                    :disabled="!formData.responsibleDeptId"
                    :placeholder="
                      !formData.responsibleDeptId
                        ? '请先选择责任科室'
                        : '请选择'
                    "
                    :roleCode="computedUserRoleCode"
                    @change="handleChangeUser"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话">
                  <el-input
                    :model-value="formData.responsibleUserPhone"
                    disabled
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </template>
      </div>
    </el-scrollbar>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="close">
          {{
            showData.receiveState === EMatterReceiveStatus['未签收']
              ? '取消'
              : '关闭'
          }}
        </el-button>
        <el-button
          v-if="showData.receiveState === EMatterReceiveStatus['未签收']"
          type="primary"
          :loading="loading"
          @click="submit()"
        >
          签收
        </el-button>
        <el-button
          v-else-if="EMatterReceiveStatus['已签收']"
          type="primary"
          :loading="loading"
          @click="submit()"
        >
          更新
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { computed, nextTick, reactive, ref, useTemplateRef, watch } from 'vue'
import { FormInstance, FormRules } from 'element-plus'
import MatterInfo from '@/components/showInfo/MatterInfo.vue'
import {
  getMatterReceiveDetail,
  saveReceive,
  updateReceive,
} from '@/api/mission/receive'
import UnitSelect from '@/components/unit/UnitSelect.vue'
import useUserStore from '@/stores/user'
import { EDetailType } from '@/views/application/typings'
import { EMatterReceiveStatus } from '@/components/statusShow/util'
import UserSelect from '@/components/user/UserSelect.vue'
import { Message } from '@/hooks/message'

const emit = defineEmits(['update'])
const matterInfo = useTemplateRef<InstanceType<typeof MatterInfo>>('matterInfo')
const formRef = useTemplateRef<FormInstance>('formRef')

const userStore = useUserStore()

const dialogVisible = ref(false)
const loading = ref(false)
const tabName = ref('matterInfo')
const rowData = reactive({
  matterId: null,
  id: null,
})
const formData = reactive({
  unitId: null,
  responsibleLeaderId: null,
  responsibleLeaderPhone: null,
  responsibleDeptId: null,
  responsibleUserId: null,
  responsibleUserPhone: null,
})
const initResponsibleDeptId = ref(false)
watch(
  () => formData.responsibleDeptId,
  () => {
    if (initResponsibleDeptId.value) {
      initResponsibleDeptId.value = false
      return
    }
    formData.responsibleUserId = null
  },
)

const showData = ref({
  receiveState: null,
})

const rules = ref<FormRules<typeof formData>>({
  responsibleLeaderId: {
    required: true,
    message: '请选择责任领导',
    trigger: 'change',
  },
  responsibleDeptId: {
    required: true,
    message: '请选择责任科室',
    trigger: 'change',
  },
  responsibleUserId: {
    required: true,
    message: '请选择责任人',
    trigger: 'change',
  },
})

function handleChangeLeader(val: any) {
  if (!val) {
    formData.responsibleLeaderPhone = null
    return
  }
  formData.responsibleLeaderPhone = val?.phone
}

function handleChangeUser(val: any) {
  if (!val) {
    formData.responsibleUserPhone = null
    return
  }
  formData.responsibleUserPhone = val.phone
}

defineExpose({ show })

const isApprove = ref(EDetailType.APPROVE)

const title = computed(() => {
  return isApprove.value === EDetailType.APPROVE ? '签收事项' : '事项详情'
})

const computedUserRoleCode = computed(() => {
  return isApprove.value === EDetailType.APPROVE ? 'responsibleUnitWorker' : ''
})

const computedLeaderRoleCode = computed(() => {
  return isApprove.value === EDetailType.APPROVE
    ? 'responsibleUnitChargeLeader'
    : ''
})

function show(row: any, approve = EDetailType.APPROVE) {
  dialogVisible.value = true
  isApprove.value = approve
  tabName.value = 'matterInfo'
  nextTick(async () => {
    Object.assign(rowData, {
      matterId: row.matterId,
      id: row.id,
    })
    await setMatterData()
  })
}

function setFormData(matterReceive: any) {
  formData.responsibleLeaderId = matterReceive.responsibleLeaderId
  formData.responsibleLeaderPhone = matterReceive.responsibleLeaderPhone
  formData.responsibleDeptId = matterReceive.responsibleDeptId
  initResponsibleDeptId.value = true
  formData.responsibleUserId = matterReceive.responsibleUserId
  formData.responsibleUserPhone = matterReceive.responsibleUserPhone
  formData.unitId = matterReceive.unitId
}

async function setMatterData() {
  loading.value = true
  const { data } = await getMatterReceiveDetail({
    id: rowData.id,
    matterId: rowData.matterId,
  })
  if (data.status === 200) {
    await matterInfo.value.setData(data.data)
    showData.value = data.data.matterReceiveDetail
    setFormData(data.data.matterReceiveDetail)
  }
  loading.value = false
}

async function handleTabChange() {
  if (tabName.value === 'matterInfo') {
    await setMatterData()
  }
}

function close() {
  dialogVisible.value = false
  loading.value = false
  formRef.value?.resetFields()
  Object.assign(formData, {
    responsibleLeaderId: null,
    responsibleLeaderPhone: null,
    responsibleDeptId: null,
    responsibleUserId: null,
    responsibleUserPhone: null,
  })
  Object.assign(rowData, {
    matterId: null,
    id: null,
  })
  isApprove.value = EDetailType.APPROVE
  if (tabName.value === 'matterInfo') {
    matterInfo.value.reset()
  }
  tabName.value = 'matterInfo'
  initResponsibleDeptId.value = false
}

function submit() {
  formRef.value.validate(async (bool: boolean) => {
    if (!bool) {
      return
    }

    const postData = {
      ...rowData,
      responsibleLeaderId: formData.responsibleLeaderId,
      responsibleDeptId: formData.responsibleDeptId,
      responsibleUserId: formData.responsibleUserId,
      unitId: userStore.unitId,
      receiveState: EMatterReceiveStatus['已签收'],
    }

    loading.value = true
    if (showData.value.receiveState === EMatterReceiveStatus['未签收']) {
      const { data } = await saveReceive(postData)
      if (data.status === 200) {
        Message({
          message: data.message,
          type: 'success',
        })
        emit('update')
        close()
      }
    } else if (showData.value.receiveState === EMatterReceiveStatus['已签收']) {
      const { data } = await updateReceive(postData)
      if (data.status === 200) {
        Message({
          message: data.message,
          type: 'success',
        })
        emit('update')
        close()
      }
    }
    loading.value = false
  })
}
</script>

<style scoped lang="scss"></style>
